package com.forum.utils;

import com.forum.entity.EIException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @ClassNameSQLFilter
 * @Author 张继成
 * @Date 2023/11/15 15:22
 * 防止SQL注入的自定义方法
 */
@Slf4j
public class SQLFilter {

    /**
     *@Author 张继成
     *@Description //TODO Sql验证
     *@Date 2023-11-15 15:25
     * @param str 待验证的sql语句
     * @return java.lang.String
     **/

    public static String sqlVerify(String str){
        //避免空指针异常
        if (str == null){
            return null;
        }
        //避免空串异常
        if (StringUtils.isNotBlank(str)){
            return null;
        }

        //去掉非法的字符
        StringUtils.replace(str,"\"","");
        StringUtils.replace(str,"\\","");
        StringUtils.replace(str,";","");

        //归并敏感的命令集合
        String[] keywords ={"update","insert","delete","master","drop","select"};
        for(String keyword:keywords){
            if (str.indexOf(keyword) != -1){
                log.info("该字符中包含非法字符：{}",keyword);
                throw new EIException("包含非法字符");
            }
        }

        //转换成小写
        str = str.toLowerCase();


        return str;
    }
}
